<?php

namespace Ignus\View\Loader;

use Ignus\View\LoaderInterface;
use Ignus\View\Error\Loader;

class ChainLoader implements LoaderInterface
{
    /**
     * @var \Ignus\View\LoaderInterface[]
     */
    protected $loaders;

    /**
     * @param array|\Ignus\View\LoaderInterface[] $loaders
     */
    public function __construct(array $loaders = array())
    {
        $this->loaders = array();
        foreach ($loaders as $loader) {
            $this->addLoader($loader);
        }
    }

    /**
     * @param \Ignus\View\LoaderInterface $loader A Loader instance
     */
    public function addLoader(LoaderInterface $loader)
    {
        $this->loaders[] = $loader;
    }

    /**
     * @param  string $name The name of the template to load
     * @return string The template source code
     */
    public function getSource($name)
    {
        foreach ($this->loaders as $loader) {
            /** @var \Ignus\View\LoaderInterface $loader */
            try {
                return $loader->getSource($name);
            }
            catch (Loader $e) {
            }
        }

        throw new Loader(sprintf('Template "%s" is not defined.', $name));
    }

    /**
     * @param  string $name The name of the template to load
     * @return string The cache key
     */
    public function getCacheKey($name)
    {
        foreach ($this->loaders as $loader) {
            /** @var \Ignus\View\LoaderInterface $loader */
            try {
                return $loader->getCacheKey($name);
            }
            catch (Loader $e) {
            }
        }

        throw new Loader(sprintf('Template "%s" is not defined.', $name));
    }

    /**
     * @param string $name The template name
     * @param integer $time The last modification time of the cached template
     * @return boolean True if template is fresh
     */
    public function isFresh($name, $time)
    {
        foreach ($this->loaders as $loader) {
            /** @var \Ignus\View\LoaderInterface $loader */
            try {
                return $loader->isFresh($name, $time);
            }
            catch (Loader $e) {
            }
        }

        throw new Loader(sprintf('Template "%s" is not defined.', $name));
    }
}
